using System.Collections.Generic;
using UnityEngine;

public class GameObjectPool
{
    static GameObjectPool mInstance;

    public static GameObjectPool Instance
    {
        get
        {
            if(mInstance == null)
                mInstance = new GameObjectPool();
            return mInstance;
        }
    }

    Dictionary<string, Stack<GameObject>> mPools;
    public static Vector3 PoolsPos = new Vector3(9999, 9999, 9999);
    public static Transform GameObjectPoolRoot;

    public void Init()
    {
        GameObjectPoolRoot = new GameObject("GameObjectPoolRoot").transform;   
        
        mPools = new Dictionary<string, Stack<GameObject>>();
        CreatePool("normal_1", 35);
        CreatePool("normal_2", 35);
        CreatePool("normal_3", 35);
        CreatePool("normal_4", 35);
        CreatePool("normal_5", 35);
        CreatePool("grid", 81);
        
        GameObject.DontDestroyOnLoad(GameObjectPoolRoot);
    }

    public Stack<GameObject> CreatePool(string name, int initialCount)
    {
        if (!mPools.TryGetValue(name, out var pool))
        {
            pool = new Stack<GameObject>(initialCount);
            for (int i = 0; i < initialCount; i++)
            {
                GameObject go = Instantiate(name, PoolsPos);
                go.transform.SetParent(GameObjectPoolRoot);
                pool.Push(go);
            }
            mPools.Add(name, pool);
        }

        return pool;
    }

    public GameObject SpawnGo(string name, Vector3 pos, int initialCount = 20)
    {
        GameObject go = null;
        var pool = CreatePool(name, initialCount);
        if (pool.Count > 0)
        {
            go = pool.Pop();
            go.transform.position = pos;
        }
        else
            go = Instantiate(name, pos);

        return go;
    }

    public void DespawnGo(string name, GameObject go)
    {
        go.transform.SetParent(GameObjectPoolRoot);
        go.transform.position = PoolsPos;
        var pool = CreatePool(name, 5);
        pool.Push(go);
    }

    GameObject Instantiate(string name, Vector3 pos)
    {
        //Debug.Log($"创建：{name}");
        return GameObject.Instantiate(Resources.Load<GameObject>(name), pos, Quaternion.identity);
    }
}